package com.xiaodeng.xdblogspringboot.controller;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.util.StringUtil;
import com.xiaodeng.xdblogspringboot.exception.ArticleException;
import com.xiaodeng.xdblogspringboot.interceptors.AdminInterceptor;
import com.xiaodeng.xdblogspringboot.interceptors.LoginInterceptor;
import com.xiaodeng.xdblogspringboot.pojo.Article;
import com.xiaodeng.xdblogspringboot.pojo.PageBean;
import com.xiaodeng.xdblogspringboot.pojo.Result;
import com.xiaodeng.xdblogspringboot.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import static com.xiaodeng.xdblogspringboot.constant.RedisConstants.*;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ObjectMapper objectMapper;



    /**
     * 文章列表（用户版本）
     *
     * @param pageNum      页码
     * @param pageSize     页面大小
     * @param title        标题
     * @param categoryName 类别名称
     * @return 结果<Page Bean < 文章>>
     */

    @GetMapping("/articlelist")
    public Result<PageBean<Article>> articlelist(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) List<String> categoryName){

        PageBean<Article> pb = articleService.articlelist(pageNum,pageSize,title,categoryName);
        return Result.success(pb);
    }

    /**
     * 文章列表（包括隐藏的）
     *
     * @param pageNum      页码
     * @param pageSize     页面大小
     * @param title        标题
     * @param categoryName 类别名称
     * @return 结果<Page Bean < 文章>>
     */
    @AdminInterceptor.AdminIntercept
    @GetMapping("/articleList")
    public Result<PageBean<Article>> articleList(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) List<String>  categoryName){
        PageBean<Article> pb = articleService.articleList(pageNum,pageSize,title,categoryName);
        return Result.success(pb);
    }


    /**
     * 添加文章
     *
     * @param article    品
     * @param categoryId 类别 ID
     * @return 结果
     */
    @LoginInterceptor.GlobalJwtIntercept
    @PostMapping("addarticle")
    public Result addarticle(@Validated @RequestBody Article article, @RequestParam List<String> categoryId){
        articleService.addarticle(article,categoryId);
        return Result.success("提交成功,请等待管理员审核");
    }

    /**
     * 查询单篇文章
     *
     * @param articleId 文章 ID
     * @return 结果<文章>
     */
    @GetMapping("getarticle")
    public Result<Article> getarticle(@RequestParam Integer articleId){
        Article article = articleService.getarticle(articleId);
        return Result.success(article);
    }
    /**
     * 删除文章
     */
    @LoginInterceptor.GlobalJwtIntercept
    @DeleteMapping("delArticle")
    public Result delArticle(@RequestParam Integer articleId) {
        articleService.delArticle(articleId);
        return Result.success("删除成功");
    }
    // TODO 更新博客文章

/*    //  热点文章浏览 （使用string类型实现）
    @GetMapping("hotArticles")
    public Result<List<Article>> getHotArticles(@RequestParam(defaultValue = "10") int limit) {
        // 从 Redis 中获取热门文章
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String hotArticlesJson = operations.get(HOT_ARTICLES_KEY);
        List<Article> hotArticles;
        try {
            if (hotArticlesJson == null) {
                // 从数据库中查询浏览量最高的文章
                hotArticles = articleService.getHotArticles(limit);
                // 将结果转为 JSON 字符串并存储到 Redis
                String json = objectMapper.writeValueAsString(hotArticles);
                operations.set(HOT_ARTICLES_KEY, json, 1, TimeUnit.HOURS);
            } else {
                // 从 JSON 字符串反序列化为 List<Article>
                hotArticles = objectMapper.readValue(hotArticlesJson, new TypeReference<List<Article>>() {});
            }
        } catch (Exception e) {
            throw new RuntimeException("处理热门文章时出错", e);
        }
        return Result.success(hotArticles);
    }*/
/**
 * 获取热门文章列表（zset）
 *
 * @param limit 返回文章的数量，默认为10
 * @return 热门文章列表
 */
@GetMapping("hotArticles")
public Result<List<Article>> getHotArticles(@RequestParam(defaultValue = "5") int limit) {
    // 操作Redis中的有序集合
    ZSetOperations<String, String> zSetOperations = stringRedisTemplate.opsForZSet();
    // 操作Redis中的Hash数据结构
    HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();
    // 从Redis的有序集合中获取热门文章的ID
    Set<String> hotArticleIds = zSetOperations.reverseRange(HOT_ARTICLES_KEY, 0, limit - 1);

    // 初始化热门文章列表
    List<Article> hotArticles = new ArrayList<>();
    // 如果Redis中没有热门文章数据，则从数据库中查询
    if (hotArticleIds == null || hotArticleIds.isEmpty()) {
        hotArticles = articleService.getHotArticles(limit);

        // 将数据库查询结果存储到Redis的有序集合和Hash中
        for (Article article : hotArticles) {
            zSetOperations.add(HOT_ARTICLES_KEY, article.getId().toString(), article.getViewCount());
            hashOperations.put(ARTICLE_TITLE_KEY, article.getId().toString(), article.getTitle());
        }
        // 设置过期时间为1小时（3600秒）
        stringRedisTemplate.expire(HOT_ARTICLES_KEY, 4, TimeUnit.HOURS);
        stringRedisTemplate.expire(ARTICLE_TITLE_KEY, 4, TimeUnit.HOURS);
    } else {
        //批量ID查询
        //List<Article> articles = articleService.getArticlesByIds(hotArticleIds);
       // 将获取到的文章放入 hotArticles 列表
        //hotArticles.addAll(articles);
        // 从Redis的有序集合中获取文章ID，并从Hash中获取对应的文章标题
        for (String articleId : hotArticleIds) {

            Article article = articleService.getarticle(Integer.valueOf(articleId));
            if (article != null) {
                String title = hashOperations.get(ARTICLE_TITLE_KEY, articleId);
                article.setTitle(title); // 设置文章标题
                hotArticles.add(article);
            }
        }
    }
    // 返回热门文章列表
    return Result.success(hotArticles);
}


     //浏览量增加


    /**
     * 增加查看次数
     *
     * @param articleId 文章ID
     * @return 结果<长>
     */
    @GetMapping("viewCount")
    public Result<Long> incrementViewCount(@RequestParam Long articleId) {
        Long longResult = articleService.incrementViewCount(articleId);
        return Result.success(longResult);
    }



    /**
     * 获取浏览量
     */
    @GetMapping("getViewCount")
    public Result getViewCount(@RequestParam Long articleId) {
        String key = VIEW_COUNT_KEY + articleId;
        if (articleId == null){
            throw new ArticleException(500,"请输入文章ID");
        }
        //判断articleId是否存在
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String count = operations.get(key);
        if (count == null || StrUtil.isEmpty(count)) {
            // 如果没有记录，返回 0
            return Result.success(0);
        }
        return Result.success(count);
    }

    /**
     * 编辑文章
     * @param article 文章对象
     * @param categoryId 类别ID列表
     * @return 结果
     */
    @LoginInterceptor.GlobalJwtIntercept
    @PutMapping("editArticle")
    public Result editArticle(@Validated @RequestBody Article article, @RequestParam List<String> categoryId) {
        articleService.editArticle(article, categoryId);
        return Result.success("文章编辑成功");
    }



}
